package cloud.keveri.gateway.sdk;

import cloud.keveri.gateway.sdk.shutdown.ShenyuClientShutdownHook;
import cloud.keveri.registry.api.InstanceRegisterRepository;
import cloud.keveri.gateway.dto.KeveriClientConfigure;
import cloud.keveri.spi.ExtensionLoader;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 作者：沈自在
 **/
public final class ClientRegisterRepositoryFactory {
    private static final Map<String, InstanceRegisterRepository> REPOSITORY_MAP = new ConcurrentHashMap<>();

    /**
     * New instance shenyu client register repository.
     */
    public static InstanceRegisterRepository newInstance(final KeveriClientConfigure configure) {
        if (!REPOSITORY_MAP.containsKey(configure.getRegisterType())) {
            InstanceRegisterRepository result = ExtensionLoader.getExtensionLoader(InstanceRegisterRepository.class).getJoin(configure.getRegisterType());
            result.init(configure);
            ShenyuClientShutdownHook.set(result, configure.getProps());
            REPOSITORY_MAP.put(configure.getRegisterType(), result);
            return result;
        }
        return REPOSITORY_MAP.get(configure.getRegisterType());
    }
}
